#!/usr/bin/env python3
# -*- coding:utf-8 -*-


"""
响应结构体定义(http response)
"""

from typing import Generic, List, Optional, TypeVar
from pydantic import BaseModel, ValidationError
from src.common.error import Code, Error, ErrorLevel
from src.common.log import logger

DataT = TypeVar('DataT')


class Response(BaseModel, Generic[DataT]):
    """
    通用响应结构体定义
    """
    code: Optional[int] = Code.OK  # 错误码
    err_msg: Optional[str] = ""  # 错误信息
    dev_message: Optional[str] = ""  # 详细错误信息


def resp_ok(data: DataT = None):
    """
    返回成功响应
    :param data:
    :return:
    """
    return Response[DataT](data=data, code=Code.OK, err_msg=Error.get_message_by_code(Code.OK))


def resp_err(err: Error | ValidationError | Exception):
    """
    返回失败响应
    :param err:
    :param data:
    :return:
    """
    if isinstance(err, Error):
        if err.level == ErrorLevel.CRITICAL:
            logger.error(f"critical error, code:{err.code}, err_msg {err.message}")
        resp = Response[DataT](code=err.code, err_msg=err.message, dev_message=err.dev_message)
    elif isinstance(err, ValidationError):
        resp = Response[DataT](code=Code.BAD_REQUEST, err_msg=str(err), dev_message="")
    else:
        code = Code.INTERNAL_SERVER_ERROR
        err_msg = str(err)
        # logger.error(f"critical error, error_code:{error_code}, error_msg {error_msg}")
        logger.exception(err)
        resp = Response[DataT](code=code, err_msg=err_msg, dev_message="")

    return resp
